<?php
/**
 * Created by PhpStorm.
 * User: Lzhy ysjywz@gmail.com
 * Date: 2019/8/20
 * Time: 9:37 AM
 */
namespace app\wechat\logic;

use think\Db;

class Wuser
{
    public static function syncUser()
    {
        $wechatList = Db::table('wechat')->field('id,name,wechat_id')->select();

        $res = ['success'=>0,'msg'=>'没有查到微信消息'];
        if($wechatList){
            $msg = [];
            foreach ($wechatList as $v){
                try{
                    $_res = self::_fetchUserList($v['id']);
                }catch (\Exception $e){
                    $_res = ['success'=>0,'msg'=>$e->getMessage()];
                }
    
                if($_res['success']){
                    $msg['msg'][] = sprintf('公众号「%s」同步完成',$v['name']);
                }else{
                    $msg['msg'][] = sprintf('公众号「%s」同步失败:%s',$v['name'],$_res['msg']);
                }
            }
            $res = ['success'=>1,'msg'=>implode('<br>',$msg['msg'])];
        }
    
        return $res;
    }


    private static function _fetchUserList($id,$nextOpenId = null)
    {
        try{
            $app = new App($id);
            $wApp = $app->getApp();
            $data = $wApp->user->list($nextOpenId);
            $_res = ['success'=>0,'msg'=>$data['errmsg'] ?? '拉取用户列表失败'];
            if(isset($data['data']) && $data['data']){
                $_res = self::saveOrUpdate($data['data']['openid'],$id);
                if($_res['success'] && $data['next_openid']){
                    //self::_fetchUserList($id,$data['next_openid']);
                }else{
                    //self::_fetchUserList($id);
                }
            }
        }catch (\Exception $e){
            $_res = ['success'=>0,'msg'=>$e->getMessage()];
        }
        return $_res;
    }


    public static function saveOrUpdate($list,$id)
    {
        try{
            $data = [];
            foreach ($list as $v){
                $data[] = [
                    'openid' => $v,
                    'nickname' => 'to_be_sync',
                    'wechat_id' => $id
                ];
            }
            $res = ['success'=>0,'msg'=>'保存失败'];
            if(Db::table('wuser')->insertAll($data)){
                $res = ['success'=>1,'msg'=>'保存成功'];
            }
        }catch (\Exception $e){
            $res = ['success'=>0,'msg'=>$e->getMessage()];
        }
        return $res;
    }
}